<?php
// +----------------------------------------------------------------------
// | 麦沃德科技赋能开发者，助力中小企业发展
// +----------------------------------------------------------------------
// | Copyright (c) 2017～2024  www.wdadmin.cn    All rights reserved.
// +----------------------------------------------------------------------
// | Wdadmin系统产品软件并不是自由软件，不加密，并不代表开源，未经许可不可自由转售和商用
// +----------------------------------------------------------------------
// | Author: MY WORLD Team <bd@maiwd.cn>   www.wdadmin.cn
// +----------------------------------------------------------------------
/**
 * Class Chat
 * Desc  聊天控制器
 * Create on 2024/10/22 11:27
 * Create by wangyafang
 */

namespace app\api\controller\wddj;


use app\api\model\wddj\driver\Driver;
use app\api\model\wddj\User;
use app\api\model\wddj\user\Order;
use app\common\controller\Api;
use GatewayWorker\Lib\Gateway;

class Chat extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['travel_dialogue','index','bind','travel_dialogue_list','message_list'];

    protected $model = null;
    protected $wechat_id = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\api\model\wddj\Chat();
        $this->wechat_id = User::getWechatId($this->auth->id);
    }

    /**
     * Desc 绑定微信用户ID
     * Create on 2024/11/15 16:57
     * Create by wangyafang
     */
    public function bind()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $client_id = $this->request->post('client_id');
        if (empty($client_id)) {
            $this->error('client_id不能为空');
        }
        $wechat_id =  $this->wechat_id;
        $order_id = $this->request->post('order_id');
        if ($order_id) {
            $wechat_id = $wechat_id.'_order_id'.$order_id;
        }
        Gateway::bindUid($client_id, $wechat_id);
        $this->success('绑定成功');
    }

    /**
     * Desc 行程对话列表
     * Create on 2024/10/22 11:28
     * Create by wangyafang
     */
    public function travel_dialogue_list()
    {
        if(!$this->request->isGet()) {
            $this->error('请求类型错误');
        }
        $param = $this->request->get();
        $wechat_id = User::getWechatId($this->auth->id);


        $page = isset($param['page']) ? $param['page'] : '';
        $limit = isset($param['limit']) ? $param['limit'] : 10;
        $type = $param['type'];

        if ($type == 1) {
            $where['wechat_id'] = array('eq',$wechat_id);
        } else {
            $where['driver_wechat_id'] = array('eq',$wechat_id);
        }

        $subQuery = $this->model
            ->field('order_id, MAX(createtime) AS latest_time')
            ->where($where)
            ->group('order_id')
            ->buildSql(); // 使用 buildSql() 将子查询转化为 SQL 字符串

        // 主查询获取与子查询匹配的消息
        $data = $this->model
            ->alias('m')
            ->join([$subQuery => 'latest_messages'], 'm.order_id = latest_messages.order_id AND m.createtime = latest_messages.latest_time')
            ->order('m.createtime DESC')
            ->page($page, $limit)  // 分页
            ->select();


        foreach ($data as $k=>&$v) {
            if ($type == 1) {
                $driver_id = (new Driver())->where('wechat_id',$v->driver_wechat_id)->value('id');
                $driver_info = Driver::getDriverBaseInfo($driver_id);
                $v->name = $driver_info['name'];
                $v->avatar = $driver_info['avatar'];
                $v->latest_time = date('Y.m.d',$v->latest_time);
                $v->hidden(['id','wechat_id','driver_wechat_id','createtime']);
            } else {
                $userWechatObj = (new \app\api\model\wddj\UserWechat())->get($v['wechat_id']);
                $v->name = $userWechatObj['nickname'];
                $v->avatar = wddj_full_url('/assets/addons/wddj/img/user.png');
                $v->latest_time = date('Y.m.d',$v->latest_time);
                $v->hidden(['id','wechat_id','driver_wechat_id','createtime']);
            }
        }

        $count = $this->model
            ->alias('m')
            ->join([$subQuery => 'latest_messages'], 'm.order_id = latest_messages.order_id AND m.createtime = latest_messages.latest_time')->count();


        $this->success('请求成功',['total'=>$count,'data'=>$data]);
    }

    /**
     * Desc 消息列表
     * Create on 2024/10/22 11:28
     * Create by wangyafang
     */
    public function message_list()
    {
        if(!$this->request->isGet()) {
            $this->error('请求类型错误');
        }

        $param = $this->request->get();
        $where['order_id'] = array('eq',$param['order_id']);
        $orderObj = (new Order())->get($param['order_id']);
        if (!$orderObj) {
            $this->error('订单不存在');
        }
        if (in_array($orderObj['state'],array('adjusting','refunded','awaiting_payment','completed','cancelled'))) {
            $end = 1;
        } else {
            $end = 2;
        }

        $page = isset($param['page']) ? $param['page'] : '';
        $limit = isset($param['limit']) ? $param['limit'] : 10;
        $count = $this->model->where($where)->count();
        $order = 'id desc';
        $type = $param['type'];
        $wechat_id = User::getWechatId($this->auth->id);
        if ($type == 1) {
            $updateWhere['wechat_id'] = ['eq', $wechat_id];   // null
        } else {
            $updateWhere['driver_wechat_id'] = ['eq', $wechat_id];   // null
        }
        $this->model->where($where)->where($updateWhere)->update(['status'=>'read']);

        $data = $this->model
            ->where($where)
            ->page($page,$limit)
            ->field('*')
            ->order($order)
            ->select();

        foreach ($data as &$v) {
            if ($v['sender'] == 'user') {//用户的聊天信息
                $v->avatar = wddj_full_url('/assets/addons/wddj/img/user.png');
            } else {
                $v->avatar = wddj_full_url('/assets/addons/wddj/img/driver.png');
            }
            if (date('Y', $v->createtime) === date('Y')) {
                $v->createtime = date('m-d H:i',$v->createtime);
            } else {
                $v->createtime = date('Y-m-d H:i',$v->createtime);
            }
            $v->hidden(['wechat_id','driver_wechat_id','status']);
        }

        if (!empty($data)) {
            $data = collection($data)->toArray();

            $ids = array_column($data, 'id');

            array_multisort($ids, SORT_ASC, $data);
        }

        $this->success('请求成功',['total'=>$count,'data'=>$data,'end'=>$end]);
    }
}



 